import 'package:flutter01/pages/sqfLite/utils/object_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter01/pages/sqfLite/utils/date_time.dart';

enum TargetStatus {
  processing, //进行中
  completed, //已完成
  gaveUp, // 放弃Ut
}

class Target {
  int? id;
  String? name;
  String? description;
  int? targetDays;
  Color? targetColor;
  String? soundKey;
  List<TimeOfDay>? notificationTimes;
  DateTime? createTime;
  DateTime? giveUpTime;
  TargetStatus? targetStatus;

  Target clone() {
    return Target()
      ..id = id
      ..name = name
      ..description = description
      ..targetDays = targetDays
      ..targetColor = targetColor
      ..soundKey = soundKey
      ..notificationTimes = notificationTimes
      ..createTime = createTime
      ..giveUpTime = giveUpTime
      ..targetStatus = targetStatus;
  }

  //将从数据库中目标表中查询的目标map转换为Target对象
  static Target? targetFromMap(Map<String, dynamic> map) {
    if (ObjectUtil.isEmptyMap(map)) return null;

    Color? color;
    //（存储在数据库中为 255|255|255)
    String? colorString = map["t_colors"];
    if (!ObjectUtil.isEmptyString(colorString)) {
      List<String> items = colorString!.split('|');
      //rgb 3个颜色
      if (!ObjectUtil.isEmptyList(items) && items.length == 3) {
        try {
          color = Color.fromRGBO(
              int.parse(items[0]), int.parse(items[1]), int.parse(items[2]), 1);
        } catch (e) {}
      }
    }

    //目标推送时间段解析
    List<TimeOfDay>? notificationTimes;
    String? notificationTimesString = map["t_notification_time"];
    if(!ObjectUtil.isEmptyString(notificationTimesString)){
      var items = notificationTimesString!.split("|");
      if(!ObjectUtil.isEmptyList(items)){
        notificationTimes = [];
        items.forEach((element) {
            TimeOfDay? timeOfDay = stringToTimeOfDay(element);
            if(timeOfDay != null) notificationTimes!.add(timeOfDay);
        });
      }
    }

    //创建时间解析
    String createTimeString = map["t_create_time"];
    DateTime? createTime  = stringToDateTime(createTimeString);

    //判断目标状态
    TargetStatus? targetStatus;
    DateTime? giveUpTime;
    if(map["t_giveUp_time"] != null){
       targetStatus = TargetStatus.gaveUp;
       giveUpTime = stringToDateTime(map["t_giveUp_time"]);
    }else{
      //可能是进行中或者已完成
      //获取目标完成时间
      DateTime completedTime = createTime!.add(Duration(days:map["t_days"] as int));
      if(DateTime.now().isBefore(completedTime)){
        //进行中
        targetStatus = TargetStatus.processing;
      }else{
        // 已完成
        targetStatus = TargetStatus.completed;
      }
    }

    return Target()
      ..id = map["id"] as int
      ..name = map["t_name"] as String
      ..targetDays = map["t_days"] as int
      ..targetColor = color
      ..soundKey = map["t_sound_key"]
      ..notificationTimes = notificationTimes
      ..createTime = createTime
      ..giveUpTime = giveUpTime
      ..targetStatus = targetStatus
    ;
  }
}
